package cn.sc.summer.summerboot.listener;

import cn.sc.summer.constant.token.TokenConstant;
import cn.sc.summer.token.encrypt.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * 类名：redis-key过期监听处理类
 *
 * @author a-xin
 * @date 2023/8/29 16:00
 */
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     *
     * @param message key失效消息体-->注意message.toString()可以获取失效的key
     * @param pattern 表达式
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        log.debug("Receive expire redis key: {}", expiredKey);
        if (expiredKey.startsWith(TokenConstant.ACCESS_TOKEN_PREFIX)) {
            String token = expiredKey.replace(TokenConstant.ACCESS_TOKEN_PREFIX, "");
            TokenUtil.deleteSimpleToken(token);
        }
    }

}
